package com.solution.admin.product.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.product.entity.ProductPropertyEntity;
import com.solution.admin.product.service.ProductPropertyService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;

/**
 * 商品属性web控制层
 * @author lilp
 * @date 2017-08-30 19:01:10
 */
@RequestMapping("/productProperty")
@Controller
public class ProductPropertyController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(ProductPropertyController.class);

	@Autowired
	private ProductPropertyService productPropertyService;
	
	/**
	 * 跳转商品属性查询页面
	 * @param ProductProperty 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-08-30 19:01:10
	 */
	@RequestMapping("/toListProductPropertyPage")
	public String toListProductPropertyPage(HttpServletRequest request) {
		return "product/productProperty_list";
	}
	
	/**
	 * 跳转到商品属性模块-详情页面的属性选择列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/toProductPropertySelector")
	public String toProductPropertySelector(HttpServletRequest request) {
		return "product/productProperty_selector";
	}
	

	/**
	 * 分页查询商品属性列表
	 * @param productProperty 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-08-30 19:01:10
	 */
	@RequestMapping("/listProductPropertyPage")
	@ResponseBody
	public JSONGrid listProductPropertyPage(ProductPropertyEntity productProperty, HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String propertyName = request.getParameter("propertyName");
		String propertyValue = request.getParameter("propertyValue");
		paramMap.put("propertyName", propertyName);
		paramMap.put("propertyValue", propertyValue);
		try {
			PageBean pageBean = productPropertyService.listProductPropertyPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(),pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询商品属性失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	/**
	 * 分页查询商品属性列表 ( 其中排除指定商品属性模板中已有的属性 )
	 * @param productProperty 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-08-30 19:01:10
	 */
	@RequestMapping("/listProductPropertyPageForTemplate")
	@ResponseBody
	public JSONGrid listProductPropertyPageForTemplate(ProductPropertyEntity productProperty, HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String templateId = request.getParameter("templateId");
		String propertyName = request.getParameter("propertyName");
		String propertyValue = request.getParameter("propertyValue");
		paramMap.put("templateId", templateId);
		paramMap.put("propertyName", propertyName);
		paramMap.put("propertyValue", propertyValue);
		try {
			PageBean pageBean = productPropertyService.listProductPropertyPageForTemplate(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(),pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询商品属性失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	/**
	 * 跳转新增页面
	 * @return string 跳转页面路径
	 * @author lilp
 	 * @date 2017-08-30 19:01:10
	 */
	@RequestMapping("/toAddProductProperty")
	public String toAddProductProperty(HttpServletRequest request) {
		request.setAttribute("opFlag", "add");
		return "product/productProperty_form";
	}

	/**
	 * 跳转编辑页面
	 * @return string 跳转页面路径
	 * @author lilp
 	 * @date 2017-08-30 19:01:10
	 */
	@RequestMapping("/toUpdateProductProperty")
	public String toUpdateProductProperty(HttpServletRequest request) {
		String id = request.getParameter("id");
		request.setAttribute("id", id);
		long longId = StringUtil.isEmpty(id)?-1L:Long.parseLong(id);
		try {
			if(-1 != longId){
				ProductPropertyEntity productProperty = productPropertyService.getProductPropertyById(longId);
				request.setAttribute("ppe", productProperty);
			}
		} catch (Exception e) {
			handleException("跳转商品属性编辑页面", logger, e);
		}
		return "product/productProperty_form";
	}
	
	/**
	 * 查询商品属性
	 * @param request
	 * @return
	 */
	@RequestMapping("/listProductPropertyValue")
	@ResponseBody
	public JSONGrid listProductPropertyValue(HttpServletRequest request) {
		String id = request.getParameter("id");
		long longId = StringUtil.isEmpty(id)?-1L:Long.parseLong(id);
		try {
			if(-1 != longId){
				ProductPropertyEntity productProperty = productPropertyService.getProductPropertyById(longId);
				List<ProductPropertyEntity>  ppeList = new ArrayList<ProductPropertyEntity>();
				String[] propertyArr = productProperty.getPropertyValue().split(",");
				for (String property : propertyArr) {
					ProductPropertyEntity tmp = new ProductPropertyEntity();
					tmp.setPropertyValue(property);
					ppeList.add(tmp);
				}
				return  new JSONGrid(ppeList,ppeList.size());
			}else{
				return new JSONGrid();
			}
		} catch (Exception e) {
			handleException("查询商品属性值页面错误", logger, e);
		}
		return new JSONGrid();
	}
	
	
	/**
	 * 查询商品属性模板-属性列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/listPropductPropertyTemplatePropertyList")
	@ResponseBody
	public JSONGrid listPropductPropertyTemplatePropertyList(HttpServletRequest request) {
		String id = request.getParameter("id");
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("templateId", id);
			List<ProductPropertyEntity> ppeList = productPropertyService.listPropductPropertyTemplatePropertyList(param);
			return  new JSONGrid(ppeList,ppeList.size());
		} catch (Exception e) {
			handleException("查询商品属性模板-属性列表", logger, e);
		}
		return new JSONGrid();
	}
	
    /**
     * 根据商品ID获取属性列表（用于不使用模板）
     * 
     * @param productId
     * @return JSONGrid
     * @author xu_cc
     * @throws Exception
     *             exception
     * @Date 创建时间：2017年11月7日 上午9:23:08
     */
    @RequestMapping("/listByProductId")
    @ResponseBody
    public JSONGrid listByProductId(HttpServletRequest request, Long productId) {
        try {
            if (null != productId) {
                List<ProductPropertyEntity> ppeList = productPropertyService.listByProductId(productId);
                return new JSONGrid(ppeList, ppeList.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONGrid();
    }

	/**
	 * 新增或保存商品属性
	 * @param request 请求对象
	 * @param productPropertyEntity 商品属性实体
	 * @return
	 * @author lilp
	 * @throws UnsupportedEncodingException 
 	 * @date 2017-08-30 19:01:10
	 */
	@RequestMapping("/saveOrUpdateProductProperty")
	public String saveProductProperty(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String id = request.getParameter("id");
			long longId = StringUtil.isEmpty(id)?-1L:Long.parseLong(id);
			String propertyName = request.getParameter("propertyName");
			String propertyIntro = request.getParameter("propertyIntro");
			String sortNo = request.getParameter("sortNo");
			String[] propertyValueArr = request.getParameterValues("propertyValue");
			StringBuffer tmpBuf = new StringBuffer();
			for (int i = 0; i<propertyValueArr.length;i++) {
				if(i != propertyValueArr.length-1){
					tmpBuf.append(propertyValueArr[i]).append(",");
				}else{
					tmpBuf.append(propertyValueArr[i]);
				}
			}
			ProductPropertyEntity ppe = new ProductPropertyEntity();
			ppe.setId(longId);
			ppe.setPropertyName(propertyName);
			ppe.setPropertyIntro(propertyIntro);
			ppe.setSortNo(Integer.parseInt(StringUtil.isEmpty(sortNo)?"0":sortNo));
			ppe.setPropertyValue(tmpBuf.toString());
			ppe.setCreater(getUserName());
			
			if(-1 != longId){
				productPropertyService.updateProductProperty(ppe);
			}else{
				productPropertyService.saveProductProperty(ppe);
			}
		} catch (Exception e) {
			handleException("添加商品属性失败", logger, e);
		}
		return "redirect:/productSpec/toListProductSpecPage?tabIndex=2";
	}
	
	
	
	/**
	 * 修改商品属性排序值
	 * @param request 请求对象
	 * @return
	 * @author lilp
	 * @throws UnsupportedEncodingException 
 	 * @date 2017-08-29 14:31:56
	 */
	@RequestMapping("/updateProductPropertySort")
	@ResponseBody
	public Map<String, String> updateProductPropertySort(HttpServletRequest request) throws UnsupportedEncodingException {
		Map<String, String> resultMap = new HashMap<String, String>();
		request.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		String direction = request.getParameter("direction");
		String sortNo = request.getParameter("sortNo");
		try {
			// 修改排序值
			int result = productPropertyService.updateProductPropertySort(id,direction,sortNo);
			resultMap.put("resultCode", result>0?"1":"0");
			resultMap.put("resultMsg", result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("修改商品属性排序值错误", logger, e);
			resultMap.put("resultCode", "0");
			resultMap.put("resultMsg", "操作失败");
		}
		return resultMap;
	}
	
	
	/**
	 * 删除商品属性
	 * @param request 请求对象
	 * @return
	 * @author lilp
	 * @throws UnsupportedEncodingException 
 	 * @date 2017-08-29 14:31:56
	 */
	@RequestMapping("/deleteProductProperty")
	@ResponseBody
	public Map<String, String> deleteProductProperty(HttpServletRequest request) throws UnsupportedEncodingException {
		Map<String, String> resultMap = new HashMap<String, String>();
		String id = request.getParameter("id");
		try {
			// 删除商品属性
			int result = productPropertyService.deleteProductPropertyById(Long.parseLong(id));
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("删除商品属性错误", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return resultMap;
	}
	
	
}
